package com.jinyi.wwdeng.ui.main.fragment

import android.content.Intent
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import androidx.core.view.GravityCompat
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.jinyi.base.utils.BarUtils
import com.jinyi.lib_baseadapter.BGAOnItemChildClickListener
import com.jinyi.wwdeng.App
import com.jinyi.wwdeng.AppConfigs
import com.jinyi.wwdeng.R
import com.jinyi.wwdeng.databinding.FragmentCreditApplyFailedBinding
import com.jinyi.wwdeng.pro.ProMvpFragment
import com.jinyi.wwdeng.ui.main.adapter.CreditAuditAppsAdapter
import com.jinyi.wwdeng.ui.main.contract.CreditApplyFailedContract
import com.jinyi.wwdeng.ui.main.impl.CreditApplyFailedPresenterImpl
import com.jinyi.wwdeng.ui.user.act.UserFeedbackAct
import com.jinyi.wwdeng.ui.user.fragment.UserFragment
import com.jinyi.wwdeng.utils.event.TrackEventType
import com.jinyi.wwdeng.utils.event.TrackEventUtils
import com.jinyi.wwdeng.utils.recyclerview.LinearSpacingItemDecoration
import org.json.JSONObject

/**
 * JinYiTest
 * @Author wwdeng
 * @CreateTime: 2024/4/24 15:42
 * @Annotation：贷款申请失败
 */
class CreditApplyFailedFragment(val data: JSONObject): ProMvpFragment<CreditApplyFailedContract.View, CreditApplyFailedPresenterImpl>(), CreditApplyFailedContract.View {

    lateinit var binding: FragmentCreditApplyFailedBinding
    //推荐APP列表
    var mAppAdapter: CreditAuditAppsAdapter? = null
    override fun getRootView(inflater: LayoutInflater): View {
        binding = FragmentCreditApplyFailedBinding.inflate(inflater)
        return binding.root
    }

    override fun createPresenter(): CreditApplyFailedPresenterImpl {
        return CreditApplyFailedPresenterImpl()
    }

    override fun initView() {
        binding.parentLayout.setPadding(0, BarUtils.getStatusBarHeight(),0,0)
        binding.tvTitle.text = getString(R.string.app_name)

        //添加侧边个人中心
        addMenuFragment()

        initRefreshLayout()
        initRecyclerView()

        //可再次申请日期
        binding.tvApplyAgain.text = String.format(getString(R.string.please_apply_again_after),data.optString("againApplyDate"))
        //不显示撤销图标
        binding.ivRevoke.visibility = View.INVISIBLE
        binding.emptyLayout.emptyLayout.visibility = View.GONE
    }

    override fun initListener() {
        //个人中心
        binding.ivAvatar.setOnClickListener {
            var isOpen = binding.drawerLayout.isDrawerOpen(GravityCompat.START)
            if (isOpen){//是否打开
                binding.drawerLayout.closeDrawer(GravityCompat.START,true)
                TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_USER,"CreditApplyFailed Page Close")
            } else {
                binding.drawerLayout.openDrawer(GravityCompat.START,true)
                TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_USER,"CreditApplyFailed Page Open")
            }
        }
        //客服
        binding.ivKefu.setOnClickListener {
            onIntent(UserFeedbackAct::class.java)
            TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_CUSTOMER,"CreditApplyFailed Page")
        }
    }

    override fun initData() {
        showLoading("")
        presenter.loadRecommendAppListRequest()
    }

    /* 初始化刷新 */
    private fun initRefreshLayout() {
        //禁止加载
        binding.refreshLayout.setEnableLoadMore(false)
        binding.refreshLayout.setEnableAutoLoadMore(false)
        binding.refreshLayout.setOnRefreshListener {
            val intent = Intent(AppConfigs.Action.ACTION_PROCESS_UPDATE)
            requireContext().sendBroadcast(intent)
            presenter.loadRecommendAppListRequest()
        }
        binding.refreshLayout.setOnLoadMoreListener {
            binding.refreshLayout.finishLoadMore()
        }
    }

    /**
     * 初始化可安装App列表
     */
    private fun initRecyclerView() {
        binding.recyclerView.layoutManager = LinearLayoutManager(context)
        val topDecoration = App.dp2px(12f)
        binding.recyclerView.addItemDecoration(LinearSpacingItemDecoration(0,0,topDecoration,topDecoration))
        mAppAdapter = CreditAuditAppsAdapter(binding.recyclerView)
        binding.recyclerView.adapter = mAppAdapter!!
        binding.recyclerView.itemAnimator = DefaultItemAnimator()
        mAppAdapter!!.setOnItemChildClickListener(BGAOnItemChildClickListener { _, childView, position ->
            val item = mAppAdapter!!.getItem(position)
            if (childView.id == R.id.btnInstall) {//点击安装
                TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_CREDIT_APPLY_FAILED_RECOMMEND_APP_INSTALL,item.optString("appName"))
                val appLink = item.optString("appLink")
                if (appLink.isNotEmpty()){
                    val uri = Uri.parse(item.optString("appLink"))
                    val intent = Intent(Intent.ACTION_VIEW, uri)
                    startActivity(intent)
                }
            }
        })
    }

    /**
     * 添加侧边菜单
     */
    private fun addMenuFragment(){
        childFragmentManager
            .beginTransaction()
            .add(R.id.menuLayout, UserFragment(binding.drawerLayout)) // 此处的R.id.fragment_container是要盛放fragment的父容器
            .commitAllowingStateLoss()
    }

    /**
     * 设置推荐产品列表
     */
    override fun showRecommendAppList(appList: ArrayList<JSONObject>) {
        if (appList.size == 0){
            binding.recyclerView.visibility = View.GONE
            binding.emptyLayout.emptyLayout.visibility = View.VISIBLE
            return
        }
        binding.recyclerView.visibility = View.VISIBLE
        binding.emptyLayout.emptyLayout.visibility = View.GONE
        mAppAdapter!!.data = appList
    }

    override fun onRequestFinish() {
        super.onRequestFinish()
        hideLoading()
        binding.refreshLayout.finishRefresh()
    }

    override fun onStart() {
        super.onStart()
        TrackEventUtils.logEvent(TrackEventType.PAGE.PAGE_CREDIT_APPLY_FAILED_START,"")
    }

    override fun onDestroy() {
        super.onDestroy()
        TrackEventUtils.logEvent(TrackEventType.PAGE.PAGE_CREDIT_APPLY_FAILED_END,"")
    }
}